<template>
  <div class="login-container">
    <el-row>
      <el-col :span="6" :offset="9">
        <el-form :rules="rules" :model="params" ref="loginForm">
          <el-form-item prop="userName">
            <el-input placeholder="账号" v-model="params.userName"
              ><i slot="prefix" class="el-input__icon el-icon-user-solid"></i
            ></el-input>
          </el-form-item>
          <el-form-item prop="passWord">
            <el-input show-password placeholder="密码" v-model="params.passWord"
              ><i slot="prefix" class="el-input__icon el-icon-lock"></i
            ></el-input>
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              placeholder="验证码"
              style="width: 240px"
              v-model="params.code"
              maxlength="4"
              ><i slot="prefix" class="el-input__icon el-icon-question"></i
            ></el-input>
            <img
              @click="fetchCode"
              :src="captchaCode"
              class="login-code"
              alt=""
            />
          </el-form-item>
          <el-form-item>
            <el-button
              style="width: 100%"
              type="primary"
              round
              @click="handleLogin"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getCode, login } from "../../api/user";

export default {
  name: "Login",
  data() {
    return {
      params: {
        userName: "9999",
        passWord: "123456",
        code: "",
        uuid: "",
      },
      captchaCode: null,
      rules: {
        userName: [{ required: true, message: "请输入账号", trigger: "blur" }],
        passWord: [{ required: true, message: "请输入密码", trigger: "blur" }],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          {
            len: 4,
            message: "验证码少于4位",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.fetchCode(); //请求验证码
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  methods: {
    async fetchCode() {
      let { data } = await getCode();
      this.params.uuid = data.captchaGUID;
      this.captchaCode = data.captchaCode;
    },
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          //表单验证成功 vaild就是true
            await this.$store.dispatch("user/loginAction",this.params);
            this.$router.replace("/")
        }
      });
    },
  },
};
</script>


<style lang="scss" scoped>
.login-code {
  height: 38px;
  width: 100px;
  display: inline-block;
  vertical-align: top;
  margin-left: 10px;
}
</style>
